package com.winkey.facility.gateway.connector.gate.face.oem.baisheng;

import com.sun.jna.NativeLong;
import com.winkey.facility.gateway.connector.gate.face.FaceGateConnector;
import com.winkey.facility.gateway.service.parser.DataParse;
import com.winkey.facility.gateway.service.utils.Constants;
import com.winkey.facility.gateway.service.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author yiyingzai
 */
@Component
public class BaiShengFaceGate implements FaceGateConnector {


    private DataParse simpleDataParse;

    @Autowired
    public BaiShengFaceGate(DataParse simpleDataParse){
        this.simpleDataParse = simpleDataParse;
    }
    @Override
    public String auth(Map args) {
        long timeMill = System.currentTimeMillis();
        String sign = encryption(Constants.BS_APP_KEY+timeMill+Constants.BS_APP_SECRET);
        String result = HttpUtils.sendBSPost(Constants.BS_PREFIX+"/auth/apply/token?appId="+Constants.BS_APP_ID+"&appKey="+Constants.BS_APP_KEY+"&timestamp="+timeMill+"&sign="+sign,"","application/x-www-form-urlencoded","");
        return (String)simpleDataParse.simpleDataParse(result,String.class,"data");
    }

    public String encryption(String parameter) {
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(parameter.getBytes());
            StringBuffer buf = new StringBuffer();
            for (int offset = 0; offset < md.digest().length; offset++) {
                int i = md.digest()[offset];
                if (i < 0){i += 256;}
                if (i < 16){buf.append("0");}
                buf.append(Integer.toHexString(i));
            }
                return buf.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return null;
            }
    }

    @Override
    public void init() { }

    @Override
    public NativeLong login(String camelIp) {
        return null;
    }

    @Override
    public String logout(NativeLong logId) {
        return null;
    }

}
